#coding=utf8
import re
import random
import huayiQDB.controller.log as log

logger = log.logger
def selectInfo(pattern, str):
    """
    通过正则筛选信息
    :param self:
    :param pattern: string 规则
    :param str: string 原信息
    :return: list 结果列表
    """
    if not (pattern and str):
        raise ValueError("selectInfo方法的pattern或str参数为null")
    datalists = re.findall(pattern, str, re.S | re.M)
    if not datalists:
        raise ValueError("selectInfo方法返回null")
    return datalists

def selectInfo_num(pattern, str):
    """
    通过正则筛选信息
    :param self:
    :param pattern: string 规则
    :param str: string 原信息
    :return: list 结果列表
    """
    if not (pattern and str):
        raise ValueError("selectInfo方法的pattern或str参数为null")
    datalists = re.findall(pattern, str, re.S | re.M)
    if not datalists:
        datalists = 0
    return datalists

def selectInfo_allowNUll(pattern, str):
    """
    通过正则筛选信息
    :param self:
    :param pattern: string 规则
    :param str: string 原信息
    :return: list 结果列表
    """
    if not (pattern and str):
        raise ValueError("selectInfo方法的pattern或str参数为null")
    return re.findall(pattern, str, re.S | re.M)

def tansform_respone(str):
    """
    去除字符串中换行
    :param str: response
    :return:string
    """
    if not str:
        raise ValueError("response 返回null")
    return str.replace('\r', '').replace('\n', '')


def transform_UrltoDict(str):
    """
    字符串转换成字典
    字符串格式：{xx:'ss',...},{...},...
    :param str: {xx:'ss',...},{...},...
    :return:
    """
    UrlInfo=[]
    pattern = r'\{(.*?)\}'
    str_list = selectInfo(pattern, str)
    for str_tmp in str_list:
        oneinfolist = "".join(str_tmp).split(',')
        oneinfo = {}
        for info_tmp in oneinfolist:
            info= "".join(info_tmp).split(':')
            oneinfo[info[0]] = info[1][1:-1]
        UrlInfo.append(oneinfo)
    return UrlInfo

def selectInfo_tran(pattern, str):
    return selectInfo(pattern, tansform_respone(str))

def checkUnrefresh_mergeTwoList(list_new,list_old):
    """
    检测试题是否刷新，对于刷新后的新出的试题去重后追加到list_old,返回是否发现新试题的状态
    :param list1: 新刷出试题列表
    :param list2: 过往刷出的试题
    :return:bool

    question_detail_list = {}
    question_detail_list['question_name'] = "".join(hyu.selectInfo(pattern_course_list[1], str)).strip()
    question_detail_list['question_id'] = "".join(hyu.selectInfo(pattern_course_list[2], str)).strip()
    question_detail_list['question_answer'] = "".join(hyu.selectInfo(pattern_course_list[3], str)).strip()
    question_detail_list['question_nameid'] = hyu.selectInfo(pattern_course_list[4], str)
    question_detail_list['question_choiceValue'] = hyu.selectInfo(pattern_course_list[5], "".join(str))
    question_detail_list['question_choiceName'] = hyu.selectInfo(pattern_course_list[6], "".join(str))
    question_detail_list['question_test'] = '0'
    question_detail_list['question_correct'] = ''

    list = [question_detail_list1, question_detail_list2,...]
    """
    refresh_state = False  #本次考试题是否出现新的试题
    #new_list = list_old.copy()
    for newone in list_new:
        state = True #单题是否是新题
        for oldone in list_old:
            if newone['q_IDValue'] == oldone['q_IDValue']:
                state = False
                if oldone['q_question_correct']:
                    newone['q_question_correct'] = oldone['q_question_correct']
                    newone['q_question_correct_name'] = oldone['q_question_correct_name']
                    if int(oldone['q_question_test']) != 0:
                        newone['q_question_test'] = int(oldone['q_question_test'])-1
                    else:
                        newone['q_question_test'] = int(oldone['q_question_test'])+1

                else:
                    newone['q_question_test'] = int(oldone['q_question_test'])
        if state:
            list_old.append(newone)
            refresh_state = True
    return refresh_state

def get_checkRefreshState(list_new,list_old,check_unrefresh_state):
    """
    统计刷新未出现新试题的次数
    :param list_new:
    :param list_old:
    :param check_unrefresh_state: 上一次刷新情况
    :return:
    """
    if not checkUnrefresh_mergeTwoList(list_new, list_old):
        check_unrefresh_state = check_unrefresh_state + 1
    return check_unrefresh_state


def isObtainAllCorrectAnswer(quest_list):
    """
    检查是否列表中是否都有正确答案
    :param quest_list:
    :return:
    """
    state = True
    for onequest in quest_list:
        if not onequest['q_question_correct']:
            return False
    return state

def randomInrange(low, high):
    """
    范围内，取随机数
    :param low:
    :param high:
    :return:
    """
    random_num = int(random.random()*100)
    while ((random_num > high) or (random_num < low)):
        random_num = int(random.random()*100)
    return random_num

def fillRequestType(list, text):
    for one in list:
        one['question_type'] = text


def cookie_to_dict(cookie_list):
    """
    将列表型COOKIE转换成字典型COOKIE
    :param cookie_list: webdriver.Chrome().get_cookies()
    :return:dict
    """
    cookie_dict = {}
    for one in cookie_list:
        real_name = one["name"]
        if cookie_dict.get(real_name) and cookie_dict.get(real_name) != one.get("value"):
            cookie_dict[real_name] = cookie_dict.get(real_name) + "," + one.get("value")
        else:
            cookie_dict[real_name] = one["value"]
    return cookie_dict

def getCookie_fixNeW(OldCookie, response_header):
    """
    将原有的dict的cookie与response.
    response_header.get('Set-Cookie').decode("utf-8") 的cookie  str类型
        str类型  'shcy=user_id=ee68b7ab-fa51-4122-b4cb-ac4501035ec2; domain=91huayi.com; expires=Tue, 10-Nov-2020 16:42:35 GMT; path=/'
    :param OldCookie:
    :param response_cookie:
    :return:
    """
    pattern = r'shcy=user_id=(.*?);'
    cookie_str = response_header.get('Set-Cookie').decode("utf-8")

    user_id = selectInfo(pattern, cookie_str)
    logger.info("cookie_str:" + str(user_id[0]))
    OldCookie["shcy=user_id"] = str(user_id[0])
    OldCookie["user_id"] = str(user_id[0])
    return OldCookie


def modifyUrl(url,strs):
    """
    url 将  /course_ware/course_ware.aspx?cwid=e1649208-7078-4c14-b480-a99300ab64e1
    修改为/course_ware/course_ware_polyv.aspx?cwid=cf878dfb-7e67-4b30-ae8e-ab3401193005
    :param url:
    :return:
    """
    tmp_list = str(url).split(".")
    return str(tmp_list[0])+'_'+strs+'.'+str(tmp_list[1])

def getErrorQName(qname):
    list_tmp = qname.split("、")
    return list_tmp[1].strip()

def updatequest_list(quest_list,quest_list_history):
    for Qone in quest_list:
        for onehistory in quest_list_history:
            if not onehistory['q_question_correct']:
                if (Qone['q_IDValue'] == onehistory['q_IDValue']):
                    if not Qone['q_question_correct']:  #答题后未回答正确时，只更新test
                        onehistory['q_question_test'] = Qone['q_question_test']
                    elif Qone['q_question_correct'] and (not onehistory['q_question_correct']): #本次回答正确，但此前一直未回答正确
                        onehistory['q_question_correct'] = Qone['q_question_correct']
                        onehistory['q_question_correct_name'] = Qone['q_question_correct_name']
                        onehistory['q_question_test'] = Qone['q_question_test']
    return quest_list_history

def delNameOder(list):
    for oneline in list:
        oneline['q_name'] = getErrorQName(str(oneline['q_name']))
    return list


def getCID(text):
    pattern = 'cid=(.*?)&dept_id'
    return str(selectInfo(pattern, text)[0])

def getCWID(text):
    pattern = '\?cwid=(.*?)$'
    return str(selectInfo(pattern, text))

def get_checknums(text):
    pattern = '<div id=\'divTitle[0-9]{1}\'(.*?)</div>'
    p_list = selectInfo(pattern, text)
    return len(p_list)
